package com.loyal.loyalerp.utils;

import java.net.URLEncoder;

import javax.servlet.http.HttpSession;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;

import com.loyal.loyalerp.phone.util.RequestUtils;

public class WeixinUtil {
	public static final String WEIXIN_GET_USER_INFO = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
	public static final String WEIXIN_GET_USER_INFO_DETAIL = "https://qyapi.weixin.qq.com/cgi-bin/user/get";
	public static final String WEIXIN_GET_TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
	public static final String WEIXIN_AUTHORIZE = "https://open.weixin.qq.com/connect/oauth2/authorize";

	public static String getCodeAndRedirect(HttpServletRequest request, String url) {
		HttpSession session = request.getSession();
		if (null == session.getAttribute("ACCESS_TOKEN")) {
			String corpid = PropertiesUtil.getValue("corpid");
			String corpsecret = PropertiesUtil.getValue("corpsecret");
			if (null == corpid || null == corpsecret)
				return "phone/error";
			String jsonText = RequestUtils
					.getJsonText(WEIXIN_GET_TOKEN + "?corpid=" + corpid + "&corpsecret=" + corpsecret);
			;
			String access_token = RequestUtils.getFieldFromJsonText(jsonText, "access_token");
			session.setAttribute("ACCESS_TOKEN", access_token);
		}
		String appid = PropertiesUtil.getValue("appid");
		String agentid = PropertiesUtil.getValue("agentid");
		if (null == appid || null == agentid)
			return "phone/error";
		String encodeUrl = URLEncoder.encode(url);
		String newUrl = WEIXIN_AUTHORIZE + "?appid=" + appid + "&redirect_uri=" + encodeUrl
				+ "&response_type=code&scope=snsapi_base&agentid=" + agentid + "#wechat_redirect";
		return "redirect:" + newUrl;
	}

	public static String getUserJsonInfo(HttpSession session, String code) {
		String access_token = (String) session.getAttribute("ACCESS_TOKEN");
		if (null == access_token)
			return null;
		String url = WEIXIN_GET_USER_INFO + "?access_token=" + access_token + "&code=" + code;
		String jsonText = RequestUtils.getJsonText(url);
		String userId = RequestUtils.getFieldFromJsonText(jsonText, "UserId");
		if (null == userId)
			return null;
		String url2 = WEIXIN_GET_USER_INFO_DETAIL + "?access_token=" + access_token + "&userid=" + userId;
		String jsonText2 = RequestUtils.getJsonText(url2);
		return jsonText2;
	}
}
